﻿using PECommon;
using PEProtocol;
using PEUtils;
using PNet;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BattleServer
{
    /// <summary>
    /// 战斗进程网络服务
    /// </summary>
    public class BattleNet : ILogic
    {
        private IOCPNet<BattleToken,NetMsg> mBattleNet;
        private ConcurrentQueue<BattlePack> mMsgPackQue = new ConcurrentQueue<BattlePack>();
        private Dictionary<CMD,Action<BattlePack>> mServerHandler = new Dictionary<CMD, Action<BattlePack>>();
        public void Awake()
        {
            IOCPTool.LogFunc = (msg) => PELog.Log(msg);
            IOCPTool.WarningFunc = (msg) => PELog.Warn(msg);
            IOCPTool.ErrorFunc = (msg) => PELog.Error(msg);
            IOCPTool.ColorLogFunc = (color, msg) => { PELog.ColorLog((PEUtils.LogColor)color, msg); };

            mBattleNet = new IOCPNet<BattleToken, NetMsg>();
            mBattleNet.StartAsServer("192.168.0.100", 17688, 5000);
           
        }

        public void Destory()
        {
            mBattleNet.CloseServer();
            mMsgPackQue.Clear();
            mServerHandler.Clear();
            mBattleNet = null;
        }

        public void Update()
        {
            while (!mMsgPackQue.IsEmpty)
            {
                while (mMsgPackQue.TryDequeue(out BattlePack? basePack))
                {
                    if (mServerHandler.ContainsKey(basePack.Msg.CMD))
                    {
                        mServerHandler[basePack.Msg.CMD]?.Invoke(basePack);
                    }
                
                }
                
            }
            
        }

        public void AddServerPack(BattlePack pack)
        {
            mMsgPackQue.Enqueue(pack);   
        }

        public void AddServerHandle(CMD cmd, Action<BattlePack> pack)
        {
            if (!mServerHandler.ContainsKey(cmd))
            {
                mServerHandler.Add(cmd, pack);
            }
            else
            {
                this.LogYellow($"ServerHande is already exist this cmd: {cmd}");
            }
        }
    }

    public class BattlePack
    {
        public NetMsg Msg;
        public BattleToken Token;

        public BattlePack(NetMsg msg, BattleToken token)
        {
            this.Msg = msg;
            this.Token = token;
        }
    }
}
